﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


using EShop.BLL;
using EShop.Model;
using EShop.Common;
using System.Drawing.Printing;

namespace EShop.Client
{
    public partial class frmMerchandiseOrderManger : frmBase
    {
        public frmMerchandiseOrderManger()
        {
            InitializeComponent();
        }


        /// <summary>
        /// 是否已经完成收银
        /// </summary>
        BLL.MerchandiseOrderBLL oMerchandiseOrderBLL = new MerchandiseOrderBLL();

        MerchandiseSellBLL oSellBLL = new MerchandiseSellBLL();
        List<MerchandiseOrderDetail> aMerchandiseOrderDetailList = new List<MerchandiseOrderDetail>();

        private decimal TotalSellPrice = 0;
        private decimal TotalSalePrice = 0;
        private int TotalBuyNum = 0;

        private void frmMerchandiseOrderManger_Load(object sender, EventArgs e)
        {
            txtBarCode.Focus();
        }

        private void txtBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (string.IsNullOrEmpty(txtBarCode.Text.Trim())) return;
                string IsType = txtBarCode.Text.Trim().Substring(0, 1);
                if (IsType.Equals("B"))
                {
                    AppendBind();
                }
                else
                {
                    AppendMerchandise();
                }
                txtBarCode.SelectAll();
                txtBuyCount.Value = 1;
            }
        }

        private void AppendBind()
        {
            MerchandiseBindBLL oMerchandiseBindBLL = new MerchandiseBindBLL();
            DataTable dt = oMerchandiseBindBLL.MerchandiseBindQuery(Common.SystemLibrary.SQLQuoteName(txtBarCode.Text.Trim()));
            if (dt.Rows.Count <= 0) return;
            int index = dgvMerchandiseSeeDetail.Rows.Add();
            this.dgvMerchandiseSeeDetail.Rows[index].Cells[0].Value = dt.Rows[0]["BindID"];
            this.dgvMerchandiseSeeDetail.Rows[index].Cells[1].Value = dt.Rows[0]["BindName"];
            this.dgvMerchandiseSeeDetail.Rows[index].Cells[2].Value = dt.Rows[0]["UnitName"];
            this.dgvMerchandiseSeeDetail.Rows[index].Cells[3].Value = FormatManager.FormatDecimal(Convert.ToDecimal(dt.Rows[0]["SalePrice"]));
            this.dgvMerchandiseSeeDetail.Rows[index].Cells[4].Value = FormatManager.FormatDecimal(Convert.ToDecimal(dt.Rows[0]["SellPrice"]));
            this.dgvMerchandiseSeeDetail.Rows[index].Cells[5].Value = Convert.ToInt32(txtBuyCount.Value);
            this.dgvMerchandiseSeeDetail.Rows[index].Cells[6].Value = FormatManager.FormatDecimal(Convert.ToDecimal(dt.Rows[0]["SellPrice"]) * Convert.ToInt32(txtBuyCount.Value));
                    
        }

        /// <summary>
        /// 根据商品条码，查询该商品的信息，并实现检测库存，自动上架
        /// </summary>
        private void AppendMerchandise()
        {
            string strBarcode = SystemLibrary.SQLQuoteName(txtBarCode.Text.Trim());
            MerchandiseSell oMerchandiseSell = oSellBLL.GetSigleSellMerchandiseDetail(strBarcode);
            if (oMerchandiseSell != null)
            {
                int num=Convert.ToInt32(txtBuyCount.Value);
                if (oMerchandiseSell.SellQuantity >= num)
                {
                    int index = dgvMerchandiseSeeDetail.Rows.Add();
                    this.dgvMerchandiseSeeDetail.Rows[index].Cells[0].Value = new SubmitItem(oMerchandiseSell.Barcode, oMerchandiseSell.StockInOrder.ToString());
                    this.dgvMerchandiseSeeDetail.Rows[index].Cells[1].Value = oMerchandiseSell.MerchandiseName;
                    this.dgvMerchandiseSeeDetail.Rows[index].Cells[2].Value = oMerchandiseSell.UnitName;
                    this.dgvMerchandiseSeeDetail.Rows[index].Cells[3].Value = FormatManager.FormatDecimal(oMerchandiseSell.SellPrice);
                    this.dgvMerchandiseSeeDetail.Rows[index].Cells[4].Value = FormatManager.FormatDecimal(oMerchandiseSell.SalePrice);
                    this.dgvMerchandiseSeeDetail.Rows[index].Cells[5].Value = Convert.ToInt32(txtBuyCount.Value);
                    this.dgvMerchandiseSeeDetail.Rows[index].Cells[6].Value = FormatManager.FormatDecimal(oMerchandiseSell.SalePrice * Convert.ToInt32(txtBuyCount.Value));
                    this.txtBarCode.SelectAll();
                }
                else
                {
                    AutoToSell(strBarcode);
                }
            }
        }

        private void AutoToSell(string strBarcode)
        {
            //将商品上架
            int errorCode = oMerchandiseOrderBLL.AutoSell(strBarcode);
            if (errorCode == 0)
            {
                MessageBox.Show("更新上架信息表失败，请联系管理员");
                return;
            }
            if (errorCode == 2)
            {
                MessageBox.Show("已无库存或该商品暂未上架");
                return;
            }
            if (errorCode == 3)
            {
                MessageBox.Show("该商品暂未上架或本店无改商品销售");
                return;
            }
            AppendMerchandise();
        }

        class SubmitItem
        {
            private string barcode;

            public string Barcode
            {
                get { return barcode; }
                set { barcode = value; }
            }
            private string stockInOrder;

            public string StockInOrder
            {
                get { return stockInOrder; }
                set { stockInOrder = value; }
            }
            public SubmitItem(string strBarcode, string strStockInOrder)
            {
                this.barcode = strBarcode;
                this.stockInOrder = strStockInOrder;
            }
            public override string ToString()
            {
                return this.barcode;
            }
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            //提交收银
            List<Model.MerchandiseOrderDetail> buy = new List<MerchandiseOrderDetail>();
            int index = 0;

            TotalBuyNum = 0;
            TotalSalePrice = 0;
            TotalSellPrice = 0;

            foreach (DataGridViewRow dgvr in this.dgvMerchandiseSeeDetail.Rows)
            {
                
                object o = dgvr.Cells[0].Value;
                if (o.ToString().Substring(0, 1).Equals("B"))
                {
                    MerchandiseBindBLL oMerchandiseBindBLL = new MerchandiseBindBLL();
                    DataTable dt = oMerchandiseBindBLL.MerchandiseBindDetailQuery(o.ToString(), null);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        Model.MerchandiseOrderDetail oMerchandiseOrderDetailBind = new MerchandiseOrderDetail();
                        oMerchandiseOrderDetailBind.SerialNumber = DateTime.Now.ToString("yMMddhhmmssfff") + index.ToString();
                        oMerchandiseOrderDetailBind.Barcode = dt.Rows[i]["Barcode"].ToString();
                        oMerchandiseOrderDetailBind.StockInOrder = Convert.ToInt32(dt.Rows[i]["StockInOrder"]);
                        oMerchandiseOrderDetailBind.BuyNumber = Convert.ToInt32(dt.Rows[i]["Quantity"]);
                        oMerchandiseOrderDetailBind.SalePrice = Convert.ToDecimal(dt.Rows[i]["SalePrice"]);
                        oMerchandiseOrderDetailBind.SellPrice = Convert.ToDecimal(dt.Rows[i]["SellPrice"]);
                        oMerchandiseOrderDetailBind.UnitName = dt.Rows[i]["UnitName"].ToString();
                        oMerchandiseOrderDetailBind.MerchandiseName = dt.Rows[i]["MerchandiseName"].ToString();
                        buy.Add(oMerchandiseOrderDetailBind);
                        TotalBuyNum += oMerchandiseOrderDetailBind.BuyNumber;
                        index++;
                    }
                }
                else
                {
                    Model.MerchandiseOrderDetail oMerchandiseOrderDetailUnit = new MerchandiseOrderDetail();
                    SubmitItem item=o as SubmitItem;
                    oMerchandiseOrderDetailUnit.SerialNumber = DateTime.Now.ToString("yMMddhhmmssfff") + index.ToString();
                    oMerchandiseOrderDetailUnit.Barcode = item.Barcode;
                    oMerchandiseOrderDetailUnit.StockInOrder = Convert.ToInt32(item.StockInOrder);
                    oMerchandiseOrderDetailUnit.BuyNumber = Convert.ToInt32(dgvr.Cells[5].Value);
                    oMerchandiseOrderDetailUnit.SellPrice = Convert.ToDecimal(dgvr.Cells[3].Value);
                    oMerchandiseOrderDetailUnit.SalePrice = Convert.ToDecimal(dgvr.Cells[4].Value);
                    oMerchandiseOrderDetailUnit.UnitName = (string)dgvr.Cells[2].Value;
                    oMerchandiseOrderDetailUnit.MerchandiseName = (string)dgvr.Cells[1].Value;
                    buy.Add(oMerchandiseOrderDetailUnit);
                    TotalBuyNum += oMerchandiseOrderDetailUnit.BuyNumber;
                    index++;
                }
                TotalSalePrice += Convert.ToDecimal(dgvr.Cells["TotalPrice"].Value);
                TotalBuyNum += Convert.ToInt32(dgvr.Cells["BuyNumber"].Value);
                //TotalSellPrice += oMerchandiseOrderDetail.SellPrice * oMerchandiseOrderDetail.BuyNumber;
            }
            if (buy.Count <= 0)
            {
                this.txtBarCode.SelectAll();
                this.txtBarCode.Focus();
                return;
            }


            Bill bill = new Bill();
            bill.TotalBuyNum = this.TotalBuyNum;
            bill.TotalSalePrice = this.TotalSalePrice;
            bill.TotalSellPrice = this.TotalSellPrice;

            frmMerchandiseOrderCollect oMerchandiseOrderCollect = new frmMerchandiseOrderCollect(buy,bill);
            oMerchandiseOrderCollect.Owner = this;
            if (oMerchandiseOrderCollect.ShowDialog() == DialogResult.OK)
            {
                if (oShopConfigInfo.AutoPrintBill) PrintBill(bill);
                this.dgvMerchandiseSeeDetail.Rows.Clear();
                this.txtBarCode.Clear();
            }
            else
            { }
            
        }

        private void frmMerchandiseOrderManger_KeyPress(object sender, KeyPressEventArgs e)
        {
            this.txtBarCode.Text += e.KeyChar.ToString();
        }

        private void 删除商品ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvMerchandiseSeeDetail.Rows.Count <= 0) return;
            string strBarcode = string.Empty;
            try
            {
                int index = dgvMerchandiseSeeDetail.SelectedCells[0].RowIndex;
                if (MessageBox.Show("你确认要删除该商品吗?", "温馨提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    dgvMerchandiseSeeDetail.Rows.RemoveAt(index);
                }
            }
            catch(Exception ex)
            {
                log.Write(ex.Message);
                MessageBox.Show("操作失败，请联系管理员.");
            }
        }

        private void 清空收银ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvMerchandiseSeeDetail.Rows.Count <= 0) return;
                if (MessageBox.Show("你确认要删除所有商品吗?", "温馨提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    this.dgvMerchandiseSeeDetail.Rows.Clear();
                }
            }
            catch(Exception ex)
            {
                log.Write(ex.Message);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            删除商品ToolStripMenuItem_Click(sender, e);
        }

        private void btnClearAll_Click(object sender, EventArgs e)
        {
            清空收银ToolStripMenuItem_Click(sender, e);
        }

        private void frmMerchandiseOrderManger_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.dgvMerchandiseSeeDetail.Rows.Clear();
        }

        private void txtBuyCount_KeyPress(object sender, KeyPressEventArgs e)
        {
            int index = dgvMerchandiseSeeDetail.Rows.Count;
            if (e.KeyChar == (char)13&&index>0)
            {
                decimal totalPrice = Convert.ToDecimal(dgvMerchandiseSeeDetail.Rows[index - 1].Cells["SalePrice"].Value) * txtBuyCount.Value;
                dgvMerchandiseSeeDetail.Rows[index - 1].Cells["BuyNumber"].Value = txtBuyCount.Value.ToString();
                dgvMerchandiseSeeDetail.Rows[index - 1].Cells["TotalPrice"].Value = Common.FormatManager.FormatDecimal(totalPrice);
            }
            this.txtBuyCount.Value = 1;
        }

        private void txtBuyCount_Leave(object sender, EventArgs e)
        {
            if (this.txtBuyCount.Value < 1) txtBuyCount.Value = 1;
        }

        private void PrintBill(Bill bill)
        {
            PrintBLL.Print print = new PrintBLL.Print(bill);
            print.EmployeeID = oShopConfigInfo.LoginID;
            foreach (DataGridViewRow dgvr in this.dgvMerchandiseSeeDetail.Rows)
            {
                print.DrawString(dgvr.Cells["MerchandiseName"].Value.ToString());
                print.DrawString(dgvr.Cells["Barcode"].Value.ToString() + "     " +
                    dgvr.Cells["BuyNumber"].Value.ToString() + "  " +
                    dgvr.Cells["SalePrice"].Value.ToString() + "  " +
                    dgvr.Cells["TotalPrice"].Value.ToString());
            }
            print.DoPrint();
        }

    }
}
